package com.chat.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chat.core.dao.ChatSessionDao;
import com.chat.core.entity.ChatSession;
import com.chat.core.service.ChatSessionService;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;

/**
 * 单人聊天组(ChatSession)表服务实现类
 *
 * @author makejava
 * @since 2022-04-22 14:24:44
 */
@Service("chatSessionService")
public class ChatSessionServiceImpl extends ServiceImpl<ChatSessionDao, ChatSession> implements ChatSessionService {

    @Override
    public ChatSession addChat(ChatSession session) {
        QueryWrapper<ChatSession> wrapper = new QueryWrapper<>();
        wrapper.eq("CRT_USER_ID",session.getCrtUserId()).eq("USER_ID",session.getUserId()).or().
                eq("CRT_USER_ID",session.getUserId()).eq("USER_ID",session.getCrtUserId());
        ChatSession chatSession = this.getBaseMapper().selectOne(wrapper);
        if (chatSession==null){
            boolean save = this.save(session);
            Assert.isTrue(save,"系统出现异常！");
        }else if (chatSession.getRevision() == 0){
            chatSession.setRevision(1);
            boolean b = this.updateById(chatSession);
            Assert.isTrue(b,"系统出现异常！");
        }
        return session;
    }

    @Override
    public void updateSessionRevision(ChatSession session) {
        QueryWrapper<ChatSession> wrapper = new QueryWrapper<>();
        wrapper.eq("CRT_USER_ID",session.getCrtUserId()).eq("USER_ID",session.getUserId()).or().
                eq("CRT_USER_ID",session.getUserId()).eq("USER_ID",session.getCrtUserId());
        ChatSession chatSession = this.getBaseMapper().selectOne(wrapper);
        chatSession.setRevision(0);
        boolean b = this.updateById(chatSession);
        Assert.isTrue(b,"系统出现异常！");
    }
}
